from collections import defaultdict

import pandas as pd
from datetime import datetime


def get_quarter(date_obj):
    """
    根据日期对象（pandas.Timestamp）返回季度。
    :param date_obj: 随访日期（pandas.Timestamp 类型）
    :return: 季度（1到4）
    """
    # 如果是字符串，先转换为 pandas Timestamp
    if isinstance(date_obj, str):
        date_obj = pd.to_datetime(date_obj)

    month = date_obj.month
    if 1 <= month <= 3:
        return 1
    elif 4 <= month <= 6:
        return 2
    elif 7 <= month <= 9:
        return 3
    else:
        return 4


def error6_idf(df, dict_info_setting,columns):
    """
    检查同一身份证号的相邻随访记录（不同日期）中生理指标是否有相同值

    :param df: 随访数据 DataFrame
    :param columns: 列名列表 ['身份证号', '随访日期', '随访建议']
    :return: (样式字典, 批注列表)
    """
    styles_info = {}
    comments_info = []

    T_F = dict_info_setting["error6_idf"].split(":")[-1].strip()


    id_col, date_col = columns[0], columns[1]
    check_cols = columns[2:]
    col_names = ["随访建议"]  # 用于批注的中文名称

    # 预处理：统一日期格式并排序
    df = df.copy()
    df[date_col] = pd.to_datetime(df[date_col], errors='coerce')

    # 按身份证分组处理
    for _, group in df.groupby(id_col):
        # 按时间排序并重置索引以便获取原始行号
        sorted_group = group.sort_values(date_col).reset_index(drop=False)

        # 遍历相邻记录（跳过日期相同的比较）
        prev_date = None
        prev_index = None
        prev_values = {}

        for idx, row in sorted_group.iterrows():
            current_date = row[date_col]
            current_values = {col: row[col] for col in check_cols}

            if prev_date is not None and current_date != prev_date:
                # 仅比较不同日期的记录
                for col_en, col_zh in zip(check_cols, col_names):
                    val_prev = prev_values.get(col_en)
                    val_current = current_values.get(col_en)

                    # 处理空值情况
                    if pd.isna(val_prev) and pd.isna(val_current):
                        is_same = True
                    elif pd.isna(val_prev) or pd.isna(val_current):
                        is_same = False
                    else:
                        is_same = (val_prev == val_current)

                    if is_same:
                        # 格式化日期显示
                        date_prev_str = prev_date.strftime("%Y-%m-%d")
                        date_current_str = current_date.strftime("%Y-%m-%d")

                        # 标记前一条记录
                        styles_info[(prev_index, col_en)] = 'special'
                        comments_info.append((
                            prev_index,
                            col_en,
                            f"与后一次随访({date_current_str})的{col_zh}值相同"
                        ))

                        # 标记当前记录
                        styles_info[(row['index'], col_en)] = 'special'
                        comments_info.append((
                            row['index'],
                            col_en,
                            f"与前一次随访({date_prev_str})的{col_zh}值相同"
                        ))

            # 更新前一条记录信息
            prev_date = current_date
            prev_index = row['index']
            prev_values = current_values
    if T_F=="True":
        return styles_info, comments_info
    else:
        return {}, []


